package miao_ser

import (
	"encoding/json"
	"gitee.com/ling1314/origin-utility/db"
	"gitee.com/ling1314/origin-utility/model"
	"gitee.com/ling1314/origin-utility/modules/repository"
	"gitee.com/ling1314/origin-utility/utils"
	log "github.com/sirupsen/logrus"
	"time"
)

type vaHandler struct {
}

func NewVaHandler() *vaHandler {
	return &vaHandler{}
}

// 处理举手消息
func (s *vaHandler) getDeviceId(msg model.BaseInfo) (deviceID int64, err error) {
	// 1. 查询数据库，确认设备是否已经被收录，如果没有就插入，如果有就直接返回设备ID
	var (
		ah model.AppHost
	)
	if ah, err = repository.HostRepository.FindByHostnameAndMac(msg.HostName, msg.MAC); err != nil {
		return 0, err
	}
	if ah.HostId == 0 {
		mbs, _ := json.Marshal(msg.MemoryInfo)
		dbs, _ := json.Marshal(msg.LogicDiskInfo)
		ah = model.AppHost{
			HostId:         utils.GetSoftId(),
			HostName:       msg.HostName,
			IP:             msg.IP,
			MAC:            msg.MAC,
			Domain:         msg.Domain,
			PartOfDomain:   msg.PartOfDomain,
			SystemType:     msg.SystemType,
			BuildNumber:    msg.BuildNumber,
			OSArchitecture: msg.OSArchitecture,
			Version:        msg.Version,
			SerialNumber:   msg.SerialNumber,
			RdpPort:        msg.RdpPort,
			CPUInfo:        msg.CPUInfo,
			MemoryInfo:     string(mbs),
			LogicDiskInfo:  string(dbs),
			Status:         model.AppHostStatusActivated,
			ClusterID:      model.DefaultClusterId,
			BindUserID:     0,
			LockedUserID:   0,
			CreatedAt:      time.Now().Unix(),
		}
		if err = repository.HostRepository.Insert(&ah); err != nil {
			return 0, err
		}
	} else {
		mbs, _ := json.Marshal(msg.MemoryInfo)
		dbs, _ := json.Marshal(msg.LogicDiskInfo)
		ah.HostName = msg.HostName
		ah.IP = msg.IP
		ah.MAC = msg.MAC
		ah.Domain = msg.Domain
		ah.PartOfDomain = msg.PartOfDomain
		ah.SystemType = msg.SystemType
		ah.BuildNumber = msg.BuildNumber
		ah.OSArchitecture = msg.OSArchitecture
		ah.Version = msg.Version
		ah.SerialNumber = msg.SerialNumber
		ah.RdpPort = msg.RdpPort
		ah.CPUInfo = msg.CPUInfo
		ah.MemoryInfo = string(mbs)
		ah.LogicDiskInfo = string(dbs)
		if err = repository.HostRepository.UpdateById(&ah); err != nil {
			log.Error(err)
			return
		}
	}
	return ah.HostId, nil
}

// handleLogoffSession 处理会话注销，更新数据库
func (s *vaHandler) handleLogoffSession(m model.ClientResponse) {
	var (
		session model.HostSession
		input   model.LogoffSession
		err     error
	)
	if err = json.Unmarshal([]byte(m.Content.Result), &input); err != nil {
		log.Error(err)
		return
	}
	if session, err = repository.HostSessionRepository.FindById(input.HostSessionId); err != nil {

		return
	}
	session.WinSessionId = int(input.WinSessionId)
	session.Status = model.VaSessionStatusForWinDestroyed
	session.HoldStatus = model.VaSessionHoldForHeld
	if err = repository.HostSessionRepository.UpdateById(&session); err != nil {
		log.Error(err)
		return
	}
	return
}

func (s *vaHandler) handCpuMemoryPercent(m model.ClientResponse) {
	var (
		per model.PingPcLoad
		err error
	)
	if err = json.Unmarshal([]byte(m.Content.Result), &per); err != nil {
		log.Error(err)
		return
	}
	db.VaCacheForCpuAndMemory[m.DeviceId] = []float64{per.CPU, per.Memory}
}

func (s *vaHandler) handAppList(m model.ClientResponse) {
	var (
		appAll []model.AppInstall
		err    error
	)
	err = json.Unmarshal([]byte(m.Content.Result), &appAll)
	if err = repository.AppRepository.DeleteAppInstallByHostId(m.DeviceId); err != nil {
		log.Error(err)
		return
	}
	for i := range appAll {
		appAll[i].Id = utils.GetSoftId()
		appAll[i].HostId = m.DeviceId
		appAll[i].CreatedAt = time.Now().Unix()
	}
	if len(appAll) > 0 {
		if err = repository.AppRepository.BatchInsertAppInstallList(appAll); err != nil {
			log.Error(err)
			return
		}
	}
}
